#!/bin/bash

# Copyright (c) 2001 Alcove - http://www.alcove.com/
# Please distribute under the terms of the GNU GPL, version 2

# Author: Yann Dirson <yann.dirson@fr.alcove.com>

set -e

file=
flags=
title="zxpdf-poppler"
while [ $# -gt 0 ]
do
    case "$1" in
    -z|-g|-geometry|-remote|-rgb|-papercolor|-eucjp|-t1lib|-ps|-paperw|-paperh)
	flags="$flags $1 $2"; shift ;;
    -title) title="$2"; shift ;;
    -*) flags="$flags $1" ;;
    *.[pP][Dd][Ff])
        file="$1"; shift; pages="$@"
        if   [ -f $file ]      ; then cat=""
        elif [ -f $file.Z   ]  ; then file=$file.Z   ; cat=zcat
        elif [ -f $file.gz  ]  ; then file=$file.gz  ; cat=zcat
        elif [ -f $file.bz2 ]  ; then file=$file.bz2 ; cat=bzcat
        elif [ -f $file.xz  ]  ; then file=$file.xz  ; cat=xzcat
        else echo >&2 "ERROR: file missing \`$file'"; exit 1
	fi
        break ;;
    *.gz|*.Z) file="$1"; shift; pages="$@"; cat=zcat; break ;;
    *.bz2) file="$1"; shift; pages="$@"; cat=bzcat; break ;;
    *.xz) file="$1"; shift; pages="$@"; cat=xzcat; break ;;
    *) echo >&2 "ERROR: unknown suffix in file \`$1'"; exit 1 ;;
    esac
    shift
done

if [ $# -ge 1 ] # optional page argument
then
    echo >&2 "ERROR: Too many arguments"
fi

if [ x"$title" == x -a x"$tmp" != x ]
then
    title="zxpdf-poppler: $file"
fi

if [ -z "$cat" ]
then
    tmp="$file"
else
    tmp=$(basename "$file")
    tmp=$(tempfile -p "${tmp%.pdf*}" -s .pdf)
    $cat "$file" >"$tmp"
fi

if [ "$tmp" == "" ]; then
    exec xpdf-poppler -title $title $flags
else
    trap "rm -f \"$tmp\"" 0 1 2 15
    exec xpdf-poppler -title $title $flags "$tmp" $pages
fi
